import { getUserPermission } from "@/api/permission";
import { OriginalRouteItem } from "@/hooks/useRoute";
import { Permission } from "@/typings/api/permission";

export * from "./dictionary";
export * from "./request";

/**
 * 把一维数据转为二维数组
 * 每一个子元素包含childrenLength个元素
 *
 * @param {Array} arr - 要转换的一维数组
 * @returns {Array} - 转换的二维数组
 */
export const convertTo2DArray = <T = unknown>(arr: T[], childrenLength: number) => {
  const result = [];
  for (let i = 0; i < arr.length; i += childrenLength) {
    result.push(arr.slice(i, i + childrenLength));
  }
  return result;
};

/**
 * Promise延迟
 *
 * @param {number} delay - 指定延迟时间
 * @returns {Promise} - Promise对象
 */
export const sleep = (delay = 0) => new Promise((resolve) => setTimeout(resolve, delay));

/**
 * @description: 生成uuid
 * @return String
 */
export const getUUID = () => {
  const url_uuid = URL.createObjectURL(new Blob()); //生成一个url
  const uuid = url_uuid.toString(); //生成的url转为字符串
  URL.revokeObjectURL(url_uuid); //释放这个url
  return uuid.substr(uuid.lastIndexOf("/") + 1); //链接 / 后面的就是我们要的uuid
};

/**
 * 根据blob下载文件
 *
 * @param {Blob} blob - Blob文件内容
 * @param {string} filename - 文件名
 */
export const downloadBlob = (blob: Blob, filename: string, mineType = "application/zip"): void => {
  // 创建一个 URL 对象
  blob = new Blob([blob], { type: mineType });
  const url = window.URL.createObjectURL(blob);

  // 创建一个隐藏的 <a> 标签
  const a = document.createElement("a");
  a.style.display = "none";
  a.href = url;
  a.download = filename; // 设置下载文件名

  // 将 <a> 标签添加到文档中
  document.body.appendChild(a);

  // 触发点击事件下载文件
  a.click();

  // 清理：移除 <a> 标签和释放 URL 对象
  window.URL.revokeObjectURL(url);
  a.remove();
};

/**
 * 解析宽度值，将其转换为数字。
 *
 * @param value - 表示大小的值，可以是数字或带 px 单位的字符串。
 * @return 返回数值形式的宽度。
 */
export const parseUnitToNumber = (value?: number | string): number => {
  if (!value) return 0;
  if (typeof value === "number") {
    return value;
  } else if (typeof value === "string") {
    // 如果字符串以 'px' 结尾，则去除并转换为数字
    return parseFloat(value.replace("px", ""));
  }
  return 0;
};

/**
 *
 * @param text - 要复制的文本
 * @returns Promise<null>
 */
export const copyText = (text: string) => {
  return new Promise(async (resolve, reject) => {
    try {
      await navigator.clipboard.writeText(text);
      resolve(null);
    } catch (error) {
      try {
        const input = document.createElement("textarea");
        input.value = text;
        document.body.appendChild(input);
        input.select();
        document.execCommand("copy");
        document.body.removeChild(input);
        resolve(null);
      } catch (error) {
        reject(error);
      }
    }
  });
};

export const getCachePermission = async (realTime = false): Promise<Permission[]> => {
  const storedData = localStorage.allPermission;
  if (storedData && !realTime) return JSON.parse(storedData);
  const { data } = await getUserPermission();
  localStorage.allPermission = JSON.stringify(data);
  return data;
};

export const getPermissions = async (realTime = false) => {
  try {
    const permission = await getCachePermission(realTime);
    const loop = (list: Permission[]): OriginalRouteItem[] => {
      return list
        .filter((item) => ["menu", "route"].includes(item.type))
        .map((item) => {
          const obj: Partial<OriginalRouteItem> = {};
          if (item.path) obj.path = item.path;
          if (!item.path && item.key) obj.path = item.key;
          if (item.component) obj.component = item.component;
          if (item.icon) obj.icon = item.icon;
          obj.label = item.name;
          obj.meta = { type: item.type as "menu" | "route" };
          if (item.children) return { ...obj, children: loop(item.children as Permission[]) };
          return obj;
        }) as OriginalRouteItem[];
    };
    return loop(permission);
  } catch {
    return [];
  }
};
